<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue</title>
</head>
<body>
<div id="app">
    <h1>{{ count }}</h1>
    <button @click="increment">+1</button>
</div>
<div id="app1">
    <h1>{{ count }}</h1>
    <button @click="increment">+1</button>
</div>

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.5.1/dist/vuex.js"></script>
<script>
    // 声明状态管理机
    const store = new Vuex.Store({
        state: {
            count: 0 // 也可以是对象
        },
        mutations: {
            increment(state) {
                state.count ++;
            }
        }
    });

    let vm = new Vue({
        el: "#app",
        data: {
            count: 0,
        },
        methods: {
            increment() {
                // 必须通过commit方法调用来改变数据，不能直接通过属性赋值
                this.$store.commit('increment');
                // commit实际上是采用type， handle形式，根据type触发handler通知其他使用该状态的对象，发送一个事件
                // 等同于：
                // this.$store.commit({
                //     type: 'increment'
                // });

                // console.log(this.$store.state.count);
                this.count = this.$store.state.count;
            }
        },
        // 注入状态管理器
        store: store
    });

    let vm1 = new Vue({
        el: "#app1",
        data: {
            count: 0
        },
        methods: {
            increment() {
                this.$store.commit('increment');
                // console.log(this.$store.state.count);
                this.count = this.$store.state.count;
            }
        },
        // 注入状态管理器
        store,
        watch: {
            // 监听状态变化
            '$store.state.count': function (newVal, oldVal) {
                console.log(newVal, oldVal);
                this.count = this.$store.state.count
            }
        }
    });

</script>
</body>
</html>
